package cn.ciis.basic.plugin;

import cn.ciis.basic.kit.CiisKit;
import cn.ciis.server.CiisAioHandler;
import cn.ciis.server.CiisPacket;
import cn.ciis.server.CiisServerListener;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.IPlugin;
import org.tio.core.intf.Packet;
import org.tio.server.ServerTioConfig;
import org.tio.server.TioServer;
import org.tio.server.intf.ServerAioHandler;
import org.tio.server.intf.ServerAioListener;

import java.io.IOException;

public class CiisPlugs implements IPlugin {


  /** handler, 包括编码、解码、消息处理 */
  public static ServerAioHandler ciisAioHandler = new CiisAioHandler();

  /** 事件监听器，可以为null，但建议自己实现该接口，可以参考showcase了解些接口 */
  public static ServerAioListener ciisAioListener = new CiisServerListener();

  /** 一组连接共用的上下文对象 */
  public static ServerTioConfig ciisServerTioConfig =
          new ServerTioConfig("ciis-server", ciisAioHandler, ciisAioListener);

  /** tisServer对象 */
  public static TioServer ciisServer = new TioServer(ciisServerTioConfig);

  private CiisHandler businessHandler = null;//Aop.get(BusinessHandler.class);

  /**
   * 类扫描，默认不开启
   */
  private boolean classScan = false;

  /**
   * 类扫描包
   */
  private String scanPackage = "";


  public void setScanPackage(String scanPackage) {
    this.scanPackage = scanPackage;
  }


  public void setClassScan(boolean classScan) {
    this.classScan = classScan;
  }

  @Override
  public boolean start() {
    Prop p = PropKit.use("config/ciis.setting");
    initHandler();
    ciisServerTioConfig.setHeartbeatTimeout(Long.valueOf(String.valueOf(CiisKit.strToMath(p.get("heartbeat", "0")))));
    boolean flag = false;
    try {
      ciisServer.start(p.get("serverIp",null), p.getInt("port",20201));

      if(PropKit.getBoolean("israte",true)){
        LogKit.info("t-io流量控制已开启");
      }else{
        LogKit.warn("t-io流量控制未开启");
      }

      flag = true;
    } catch (IOException e) {
      e.printStackTrace();
    }
    return flag;
  }

  @Override
  public boolean stop() {
    if (ciisServer!=null){
      return ciisServer.stop();
    }
    return true;
  }

  private void initHandler(){
    LogKit.info("t-io初始化handler");
    if(this.classScan){
      businessHandler=CiisHandlerFactory.getHandler(scanPackage);
    }
    LogKit.info("t-io handler初始化完成");
  }

  public void doBusinessHandler(Packet packet, CiisSessionContext ciisSessionContext){
    if(businessHandler !=null){
      businessHandler.handle((CiisPacket) packet, ciisSessionContext);
    }else {
      LogKit.error("没有添加任何业务处理Handler");
    }

  }


}
